package com.ztom.top100;

/**
 * 两数相加
 * <p>
 * https://leetcode-cn.com/problems/add-two-numbers/
 *
 * @author ZhangTao
 */
public class Code02AddTwoNumbers {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        return process(l1, l2, 0);
    }

    private ListNode process(ListNode l1, ListNode l2, int sum) {
        if (l1 == null && l2 == null) {
            // 如果都走完最高位了, 考察是否还有进位信息
            return sum == 0 ? null : new ListNode(sum);
        }
        if (l1 != null) {
            sum += l1.val;
            l1 = l1.next;
        }
        if (l2 != null) {
            sum += l2.val;
            l2 = l2.next;
        }
        // 取累加和的各位, 并传递进位信息
        return new ListNode(sum % 10, process(l1, l2, sum / 10));
    }
}
